public class MyListNode {
    class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode() {
        }
    }

    public void add(int val) {
        ListNode newNode = new ListNode(val);
        if (head == null) {
            head = newNode;
            return;
        }
        ListNode cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = newNode;
    }

    public ListNode get(int index) {
        ListNode cur = head;
        while (index != 1) {
            cur = cur.next;
            index--;
        }
        return cur;
    }

    public void display() {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public ListNode head;

    //链表内指定区间的反转
    public ListNode reverseBetween(ListNode head, int m, int n) {
        // write code here
        if (m == n) {
            return head;
        }
        m = m - 1;
        n = n - 1;
        int len = n - m;
        //找到m下标的节点
        ListNode cur = head.next;
        ListNode prev = head;
        ListNode pNode = head;
        int flag = 0;
        while (m != 0) {
            if (m == 1) {
                flag = 1;
                pNode = prev;
            }
            prev = prev.next;
            cur = cur.next;
            m--;
        }
        while (cur != null && len > 0) {
            ListNode curN = cur.next;
            cur.next = prev;
            prev = cur;
            cur = curN;
            len--;
        }
        if (flag == 0) {
            pNode.next = cur;
            head = prev;
        } else {
            pNode.next.next = cur;
            pNode.next = prev;
        }
        return head;

    }
}
